package com.depth.viewer.utils.json
{
	public class JSONEncoder
	{
		public function JSONEncoder()
		{
		}
		private var unescapes:Object={"\b":"b","\f":"f","\n":"n","\r":"r","\t":"t"};

   		private var escapePtn:RegExp=/["\b\f\n\r\t\\]/g;//"

    	private var controlPtn:RegExp=/\x00-\x19/g;

    

	    public function encode(obj:*):String {
	
	        var str:String=null;
	
	        var bool:Boolean=false;
	
	        if(obj===null)return "null";
	
	        if(obj===undefined)return "undefined";
	
	        if(obj is String)return encodeString(obj);
	
	        if(obj is Array){
	
	            str="[";
	
	            for (var i:int=0,j:int=obj["length"];i<j;i++){
	
	                bool?(str+=","):(bool=true);
	
	                str+=encode(obj[i]);
	
	            }
	
	            return str+"]";
	
	        }
	
	        if(obj["constructor"]==Object){
	
	            str="{";
	
	            for (var k:String in obj){
	
	                bool?(str+=","):(bool=true);
	
	                str+=encodeString(k)+":"+encode(obj[k]);
	
	            }
	
	            return str+"}";
	
	        }
	
	        return obj;
	
	    }
	
	    
	
	    private function escapeRepl(...args):String {
	
	        return "\\"+(unescapes[args[0]]||args[0]);
	
	    }
	
	    
	
	    private function controlRepl(...args):String {
	
	        var hexCode:String=String(args[0]).charCodeAt(0).toString(16);
	
	        if (hexCode.length==1)hexCode="0"+hexCode;
	
	        return "\\x"+hexCode;
	
	    }
	
	    
	
	    private function encodeString(str:String):String {
	
	        str=str.replace(escapePtn,escapeRepl);
	
	        str=str.replace(controlPtn,controlRepl);
	
	        return "\""+str+"\"";
	
	    }
	}
}